package com.xinghen.ace.common.rest;

import com.github.pagehelper.PageInfo;
import com.xinghen.ace.common.biz.BaseBiz;
import com.xinghen.ace.common.constant.CommonConstants;
import com.xinghen.ace.common.model.Query;
import com.xinghen.ace.common.response.RestResult;
import com.xinghen.ace.common.util.ThreadContextHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * @author xinghen
 * @ClassName: BaseController
 * @Package: com.xinghen.ace.common.rest
 * @Description controller层 基类
 * @create 2018-05-04 14:10
 */
@Slf4j
@SuppressWarnings("unchecked")
public class BaseController<B extends BaseBiz, E> {

    @Autowired
    protected HttpServletRequest request;

    @Autowired
    protected B biz;

    /**
     * 添加数据
     *
     * @param entity
     * @return
     */
    @PostMapping("")
    @ResponseBody
    public RestResult<E> add(@RequestBody E entity) {
        biz.insertSelective(entity);
        return RestResult.ok();
    }

    /**
     * 查询数据
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    @ResponseBody
    public RestResult<E> get(@PathVariable int id) {
        E data = (E) biz.selectById(id);
        return RestResult.ok(data);
    }

    /**
     * 修改数据
     *
     * @param entity
     * @return
     */
    @PutMapping("/{id}")
    @ResponseBody
    public RestResult<E> update(@RequestBody E entity) {
        biz.updateSelectiveById(entity);
        return RestResult.ok();
    }

    /**
     * 删除数据
     *
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    @ResponseBody
    public RestResult<E> remove(@PathVariable int id) {
        biz.deleteById(id);
        return RestResult.ok();
    }

    /**
     * 获取所有数据
     *
     * @return
     */
    @GetMapping("/all")
    @ResponseBody
    public RestResult<List<E>> all() {
        List<E> list = biz.selectListAll();
        return RestResult.ok(list);
    }

    /**
     * 分页查询
     *
     * @param params
     * @return
     */
    @GetMapping("/page")
    @ResponseBody
    public RestResult<PageInfo<E>> list(@RequestParam Map<String, Object> params) {
        Query query = new Query(params);
        PageInfo<E> pageInfo = biz.selectByQuery(query);
        return RestResult.ok(pageInfo);
    }

    /**
     * 获取当前用户名
     *
     * @return
     */
    public String getCurrentUserName() {
        return (String) ThreadContextHelper.get(CommonConstants.CONTEXT_KEY_USER_NAME);
    }

}
